import axios from 'axios';

// 服务地址
let thirdInterface = axios.create({
  // baseURL: '',
  //   withCredentials: true,
  headers: {},
  // responseType: 'json',
});

/**
 * 封装post请求(以formData提交)
 * @param url
 * @param params
 * @param config (相关请求配置,默认为{})
 * @returns {Promise}
 */
export function fetchFD(url, params = {}, config) {
  let _config = config || {};

  // 转换成FormData形式,传递参数给后台
  if (Object.prototype.toString.call(params) === "[object Object]") {
    let formData = new FormData();
    for (let key in params) {
      if (params.hasOwnProperty(key)) {
        formData.append(key, params[key]);
      }
    }
    return new Promise((resolve, reject) => {
      thirdInterface.post(url, formData, _config)
        .then(response => {
          resolve(response.data);
        }, err => {
          reject(err);
        })
    })
  } else {
    console.log('传递的参数为对象形式!');
  }
}

/**
 * 封装get方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function fetchGet(url, params = {}) {
  return new Promise((resolve, reject) => {
    thirdInterface.get(url, {
      params: params
    }).then(response => {
      resolve(response);
    }).catch(err => {
      reject(err)
    })
  });
}